import React, { useState, useEffect, useRef } from "react";
import { LeftOutlined, RightOutlined } from "@ant-design/icons";
import { getBanner } from "@/api";
import styles from "./index.less";

const Swiper: React.FC = () => {
  const [banners, setBanners] = useState<any[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const timer = useRef<any>();

  const slider = () => {
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      clearTimeout(timer.current);
      if (currentIndex < 0) {
        setCurrentIndex(banners.length - 1);
      } else if (currentIndex >= banners.length - 1) {
        setCurrentIndex(0);
      } else {
        setCurrentIndex((pre) => pre + 1);
      }
    }, 3000);
  };

  useEffect(() => {
    slider();
    return () => {
      clearTimeout(timer.current);
    };
  }, [banners, currentIndex]);

  useEffect(() => {
    getBanner({}).then((res: any) => {
      setBanners(res.banners);
    });
  }, []);
  return (
    <div
      className={styles["swiper"]}
      onMouseEnter={() => clearTimeout(timer.current)}
      onMouseLeave={() => slider()}
    >
      <div className={styles["swiper-wrap"]}>
        {banners.map((banner, index) => {
          const activeClass =
            index === currentIndex ? styles["swiper-active"] : "";
          let prevClass = "";
          let nextClass = "";
          if (currentIndex === 0 && index === banners.length - 1) {
            prevClass = styles["swiper-prev"];
          } else if (index === currentIndex - 1) {
            prevClass = styles["swiper-prev"];
          }
          if (currentIndex >= banners.length - 1 && index === 0) {
            nextClass = styles["swiper-next"];
          } else if (index === currentIndex + 1) {
            nextClass = styles["swiper-next"];
          }
          return (
            <div
              className={`${styles["swiper-item"]} ${activeClass} ${prevClass} ${nextClass}`}
              key={index}
            >
              <img src={banner.imageUrl} />
            </div>
          );
        })}
        <LeftOutlined
          className={`${styles["btn"]} ${styles["prev-btn"]}`}
          onClick={() =>
            setCurrentIndex(
              currentIndex <= 0 ? banners.length - 1 : currentIndex - 1
            )
          }
        />
        <RightOutlined
          className={`${styles["btn"]} ${styles["next-btn"]}`}
          onClick={() =>
            setCurrentIndex(
              currentIndex >= banners.length - 1 ? 0 : currentIndex + 1
            )
          }
        />
      </div>
      <div className={styles["swiper-pagination"]}>
        {banners.map((item, index) => (
          <span
            className={`${index === currentIndex ? styles["active"] : ""}`}
            onMouseLeave={() => setCurrentIndex(index)}
            key={index}
          ></span>
        ))}
      </div>
    </div>
  );
};

export default Swiper;
